from rest_framework import serializers
from question.models import *
from article.models import *


class ArticleSerializer(serializers.ModelSerializer):
    '''文章序列化器'''
    class Meta:
        model = Article
        fields = '__all__'

# 用户序列化器
class UserSerializer(serializers.ModelSerializer):
    class Meta:
        model = User
        fields = ['id', 'username', 'avatar']


# 回答序列化器----------------------

class SubsSerializer(serializers.ModelSerializer):
    '''subs序列化器'''
    user_id = serializers.IntegerField()
    user = UserSerializer(many=True)
    class Meta:
        model = Reply
        fields = '__all__'


class ReplySerializer(serializers.ModelSerializer):
    '''问题评论和回答序列化器'''
    user_id = serializers.IntegerField()
    user = UserSerializer(read_only=True)
    subs = SubsSerializer(read_only=True, many=True)  # 回答评论列表
    class Meta:
        model = Reply
        fields = '__all__'


# 问题序列化器
class QuestionsSerializer(serializers.ModelSerializer):
    # {"user_id": ["This field is required."]}
    user_id = serializers.IntegerField(write_only=True)
    user = serializers.StringRelatedField()
    labels = serializers.StringRelatedField(many=True,read_only=True)  # 问题所属标签
    comment_question = ReplySerializer(many=True, read_only=True)  # 问题评论列表
    answer_question = ReplySerializer(many=True, read_only=True)    # 问题回答列表

    class Meta:
        model = Question
        fields = '__all__'


# 标签序列化器
class LabelSerializer(serializers.ModelSerializer):
    articles = ArticleSerializer(many=True)  # 标签详情-文章列表
    questions = QuestionsSerializer(many=True)
    users = serializers.StringRelatedField(many=True)

    class Meta:
        model = Label
        fields = '__all__'


# ---------------问答详情序列化器-----------------------

class AnswerSerializer(serializers.ModelSerializer):
    subs = serializers.SerializerMethodField()  # 回答评论列表  --> 类型 object []
    user = UserSerializer()
    class Meta:
        model = Reply
        fields = '__all__'
    def get_subs(self,obj):
        data = Reply.objects.filter(parent=obj)
        return ReplySerializer(data, many=True).data

class QuestionsDetailSerializer(serializers.ModelSerializer):
    user = serializers.CharField()
    labels = serializers.StringRelatedField(many=True)
    comment_question = ReplySerializer(many=True)
    answer_question = serializers.SerializerMethodField()

    class Meta:
        model = Question
        fields = '__all__'

    def get_answer_question(self,obj):
        answer =obj.replies.filter(type=2)
        return AnswerSerializer(answer, many=True).data


















